package main.controller.admin;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import main.RequestHelper;
import main.GlobalConfig;
import main.TimeHelper;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class AuthorUpdatePageController {
    @RequestMapping(value = "/authorupdate")
    public String authorUpdate(HttpServletRequest request, ModelMap modelMap, @RequestParam String id) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

        String url = "noContentInSearchPage";
        if (isAdmin) {
            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfAuthor);
            FindIterable<Document> findIterable = collection.find(new BasicDBObject("_id", new ObjectId(id)));
            MongoCursor<Document> cursor = findIterable.iterator();

            if (cursor.hasNext()) {
                Document doc = cursor.next();

                modelMap.put("title", doc.get("name").toString());
                modelMap.put("introduction", doc.get("introduction").toString());
                modelMap.put("authorId", id);
                modelMap.put("userName", account);
                modelMap.put("year2year", TimeHelper.getFormattedYear2Year());
                url = "admin/authorUpdatePage";
            }
            cursor.close();
        }
        else {
            url = "admin/adminLoginPage";
        }

        return url;
    }
}
